//
//  HXLExchangeRateViewController.m
//  On The Load
//
//  Created by 晓琳 on 15/11/6.
//  Copyright © 2015年 @@叶一闽. All rights reserved.
//

#import "HXLExchangeRateViewController.h"
#import "AppTools.h"
#import "RateModel.h"
#import "HXLSelectRateViewController.h"

@interface HXLExchangeRateViewController ()<GetRateDelegate>
@property (nonatomic, strong) UIView *calculateView;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) UILabel *scanfLable;
@property (nonatomic, strong) UILabel *resultLable;
@property (nonatomic, strong) UILabel *rateLable;

@property (nonatomic,assign)NSInteger number1, number2;
@property (nonatomic,copy)NSString *sign;

@property(retain,nonatomic) NSMutableString *string;  //NSMutableString用来处理可变对象，如需要处理字符串并更改字符串中的字符

@property (nonatomic,assign)BOOL isFirst;
@property (nonatomic, assign) CGFloat rate;
@property (nonatomic, strong) NSString *total;
@property (nonatomic, strong) NSMutableArray *countryArray;
@property (nonatomic, strong) NSMutableArray *keyArray;


@end

@implementation HXLExchangeRateViewController

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.countryArray = [NSMutableArray array];
    self.keyArray = [NSMutableArray array];
    
    self.titleArray = @[@"1",@"2",@"3",@"C",@"4",@"5",@"6",@"-",@"7",@"8",@"9",@"+",@"00",@"0",@".",@"OK"];
    UIColor *backColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"back.jpeg"]];
    [self.view setBackgroundColor:backColor];
    self.navigationController.navigationItem.title = @"汇率转换";
    self.navigationController.navigationBar.translucent =  NO;
    self.scanfLable = [[UILabel alloc] initWithFrame:CGRectMake(30*SCALEW, 30*SCALEH, (WIDTH-60) *SCALEW, 60*SCALEH)];
    //边界宽度
    self.scanfLable.layer.borderWidth = 2.0;
    self.scanfLable.layer.cornerRadius = 5.0;
    self.scanfLable.layer.borderColor = [UIColor whiteColor].CGColor;
    self.scanfLable.font = [UIFont systemFontOfSize:22];

    self.scanfLable.textAlignment = 2;
    self.scanfLable.text = @"";
    [self.view addSubview:self.scanfLable];
    
    
    self.resultLable = [[UILabel alloc] initWithFrame:CGRectMake(30*SCALEW, 120*SCALEH, (WIDTH-60) *SCALEW, 60*SCALEH)];
    self.resultLable.layer.borderWidth = 2.0;
    self.resultLable.layer.cornerRadius = 5.0;
    self.resultLable.layer.borderColor = [UIColor whiteColor].CGColor;
    self.resultLable.text = @"";
    self.resultLable.font = [UIFont systemFontOfSize:22];

    self.resultLable.textAlignment = 2;
    [self.view addSubview:self.resultLable];
    
    self.rateLable = [[UILabel alloc] initWithFrame:CGRectMake(100*SCALEW, 200*SCALEH, (WIDTH-200) *SCALEW, 30*SCALEH)];

    self.rateLable.layer.borderWidth = 2.0;
    self.rateLable.layer.cornerRadius = 5.0;
    self.rateLable.layer.borderColor = [UIColor whiteColor].CGColor;
    self.rateLable.text = @"请先选择类型";
    self.rateLable.font = [UIFont systemFontOfSize:13];
    
    self.rateLable.textAlignment = 1;
    [self.view addSubview:self.rateLable];

    
    
    self.calculateView = [[UIView alloc] initWithFrame:CGRectMake(0, 307*SCALEH, WIDTH, 360*SCALEH)];
    [self.view addSubview:self.calculateView];
    [self creatCalculateView];
    
    self.string = [[NSMutableString alloc] init];
    
    self.isFirst = YES;
    
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"类型" style:UIBarButtonItemStylePlain target:self action:@selector(selectRate:)];
    [self getAfnData:@"http://travelbox-interface.xyz.cn/currency/get?uid=suitcase&ts=1447305159087&sig=8c232ea408777baee00e2241ebf04f77"];

}

- (void) selectRate:(UIBarButtonItem *)bar {
    
    
    HXLSelectRateViewController *rateVC = [[HXLSelectRateViewController alloc] init];
    rateVC.keyArray = self.keyArray;
    rateVC.allArray = self.countryArray;
    rateVC.myDelegate = self;
    [self.navigationController pushViewController:rateVC animated:YES];
}

- (void) creatCalculateView {
    
    
    for (int i = 0; i < self.titleArray.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake((WIDTH/4)*(i%4), 60*SCALEH*(i/4), WIDTH/4, 90*SCALEH);
        [btn setTitle:[self.titleArray objectAtIndex:i] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:25];
        [self.calculateView addSubview:btn];
        btn.tag = 1000+i;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        
        
    }
    
}

- (void) btnAction:(UIButton *)btn {
    NSLog(@"tag = %ld",btn.tag);
    
    if (btn.tag == 1007 ||btn.tag == 1011) {
#warning +/-的逻辑算法
                self.sign = btn.currentTitle;

        
//        [self go:btn];
        //逻辑2...当点击运算符号,只显示运算符号
        self.scanfLable.text = @"";
        self.scanfLable.text = btn.currentTitle;
        
        
        //逻辑3...记录当前运算符号
        self.sign = self.scanfLable.text;
        
        
        //逻辑11...如果是第一次,不加判断,每次都会将number1的值赋值给number2
        if (self.isFirst) {
            
            //逻辑7...当保存第一个数字之后,点击符号时将第一个数字保存在number2上.
            self.number2 = self.number1;
            
        
    }
    }
#warning ok/等号逻辑

    if (btn.tag == 1015) {
    
        
        self.total = @"OK";
        NSLog(@"sign = %@",_total);
        if ([self.total isEqualToString:@""]) {
            
            CGFloat result = self.number2;
            self.scanfLable.text = [NSString stringWithFormat:@"%f",result];
            
            self.resultLable.text = [NSString stringWithFormat:@"%f",result *_rate];
            
        }

        if ([self.sign isEqualToString:@"+"]) {
            
            CGFloat result = self.number2 + self.number1;
            self.scanfLable.text = [NSString stringWithFormat:@"%f",result];
            
            self.resultLable.text = [NSString stringWithFormat:@"%f",result *_rate];

        }
        if ([self.sign isEqualToString:@"-"]) {
            
            CGFloat result = self.number2 - self.number1;
            NSLog(@"-- num2 = %ld",self.number2);
            self.scanfLable.text = [NSString stringWithFormat:@"%f",result];
            self.resultLable.text = [NSString stringWithFormat:@"%f",result *_rate];
        }
        
        self.number2 = [self.scanfLable.text integerValue];
//        self.sign = self.scanfLable.text;

        self.isFirst = NO;

    }
#warning C:清空逻辑

    if (btn.tag == 1003) {
        self.scanfLable.text = @"";
        self.resultLable.text = @"";
        self.number1 = 0;
        self.number2 = 0;
        self.isFirst = YES;
        self.total = @"";
//        [self clean:btn];
        
    }
#warning 00逻辑

    if(btn.tag == 1012){
        
        self.scanfLable.text = [NSString stringWithFormat:@"%ld00",self.number1];
        self.number1 = self.number1 *100;
        self.isFirst = YES;


    }
#warning 0 - 9逻辑

    if (1000 == btn.tag ||1001 == btn.tag || 1002 == btn.tag ||1004 == btn.tag || 1005 ==  btn.tag || 1006 == btn.tag || 1008 == btn.tag  ||1009 == btn.tag || 1010 == btn.tag ||1013 == btn.tag) {
        NSLog(@"============%@",btn.currentTitle);
        
//        [self shuzi:btn];
        
        //逻辑4...当再次点击数字时,判断如果前缀包含运算符号,过滤掉
        if ([self.scanfLable.text hasPrefix:@"+"] || [self.scanfLable.text hasPrefix:@"-"]) {
            
            self.scanfLable.text = @"";
            
        }
        //逻辑5...先判断前缀是否有运算符,如果有清空,然后执行下面重新赋值数字
        
        //逻辑1...第一次点击数字,获取按钮标题,然后累加显示.
        
//        if ([_total isEqualToString:@"OK"]) {
//            _scanfLable.text = btn.currentTitle;
//            self.number2 = 0;
//            self.number1 = 0;
//            _total = nil;
//
////            return;
//            
//        }else {
        NSString *string = btn.currentTitle;
        self.scanfLable.text = [NSString stringWithFormat:@"%@%@",self.scanfLable.text,string];
        
        //逻辑6... 保存第一个数字
        self.number1 = [self.scanfLable.text integerValue];
        NSLog(@"num1 = %ld",_number1);
        
//        }
    }
}

- (void)getCurrentRate:(NSNumber *)rate{
    CGFloat f = [rate floatValue];

    self.rateLable.text = [NSString stringWithFormat:@"当前汇率:%f",f];
    NSLog(@"fffff = %f",f);
    self.rate = f;
}


- (void) getAfnData:(NSString *) string {
    
    [AppTools getAFN:string andpara:nil andBlock:^(id result) {
        
        
        NSDictionary *dic = [result objectForKey:@"response"];
        for (NSString *key in dic) {
            RateModel *rate = [dic objectForKey:key];
            [self.countryArray addObject:rate];
            [self.keyArray addObject:key];
        }
        NSLog(@"%@",self.countryArray);
        
    } andfailBlock:^(id result) {
        
        
        
    }];
    
}


- (void)shuzi:(id)sender
{
    
    [self.string appendString:[sender currentTitle]];      //数字连续输入
    self.scanfLable.text=[NSString stringWithString:_string];   //显示数值
    self.number1=[self.scanfLable.text integerValue];               //保存输入的数值
    NSLog(@"self.number1  is  %ld",self.number1);
    
}

//计算方法
-(void)go:(id)sender
{
    NSLog(@"_sign = %@",_sign);

    if ([self.sign isEqualToString:@""])//当str里为空
    {
        self.number2=self.number1;
        NSLog(@"self.number2  is  %ld",self.number2);
        self.scanfLable.text=[NSString stringWithString:_string];     //只要是符号就显示数值
        [self.string setString:@""];                             //字符串清零
        self.sign=[sender currentTitle];                          //保存运算符为了作判断作何种运算
        NSLog(@"_sign = %@",_sign);
        [self.string appendString:self.sign];
        self.scanfLable.text=[NSString stringWithString:_string];     //显示数值
        [self.string setString:@""];          //字符串清零
    }
    else
    {
        //输出上次计算结果
        if ([self.sign isEqualToString:@"+"])//之前的符号是+
        {
            [self.string setString:@""];//字符串清零
            self.number2+=self.number1;//num2是运算符号左边的数值，还是计算结果
            
            //输出上次结果后判断这次输入的是何符号
            if ([[sender currentTitle]isEqualToString:@"OK"])
            {
                NSLog(@"self.number2 is %ld",self.number2);
                self.scanfLable.text=[NSString stringWithFormat:@"%ld",self.number2];
                self.sign=@"";
            }
            else if ([[sender currentTitle]isEqualToString:@"+"]||[[sender currentTitle]isEqualToString:@"-"]||[[sender currentTitle]isEqualToString:@"*"]||[[sender currentTitle]isEqualToString:@"/"])
            {
                NSLog(@"self.number2 is %ld",self.number2);
                self.scanfLable.text=[NSString stringWithFormat:@"%ld",self.number2];
                [self.string setString:@""];   //字符串清零
                self.sign=[sender currentTitle];//保存运算符为了作判断作何种运算
                NSLog(@"%@",_sign);
                [self.string appendString:self.sign];
                [self.string setString:@""];//字符串清零
            }
        }
        
        else if ([self.sign isEqualToString:@"-"])//之前的符号是-
        {
            [self.string setString:@""];//字符串清零
            self.number2-=self.number1;
            //输出上次结果后判断这次输入的是何符号
            if ([[sender currentTitle]isEqualToString:@"OK"])
            {
                NSLog(@"self.number2  is  %ld",self.number2);
                self.scanfLable.text=[NSString stringWithFormat:@"%ld",self.number2];
                self.sign=@"";
            }
            else if ([[sender currentTitle]isEqualToString:@"+"]||[[sender currentTitle]isEqualToString:@"-"]||[[sender currentTitle]isEqualToString:@"*"]||[[sender currentTitle]isEqualToString:@"/"])
            {
                NSLog(@"self.number2  is  %ld",self.number2);
                self.scanfLable.text=[NSString stringWithFormat:@"%ld",self.number2];
                [self.string setString:@""];//字符串清零
                self.sign=[sender currentTitle];//保存运算符为了作判断作何种运算
                NSLog(@"%@",_sign);
                [self.string appendString:self.sign];
                [self.string setString:@""];//字符串清零
            }
        }
        else if ([self.sign isEqualToString:@"OK"]) {
            
        }
        
    }
}


//当按下清除建时，所有数据清零
-(void)clean:(id)sender
{
    [self.string setString:@""];//清空字符
    self.number1=0;
    self.number2=0;
    self.scanfLable.text=@"0";//保证下次输入时清零
    
}

//返回键
-(void)back:(id)sender
{
    if (![self.scanfLable.text isEqualToString:@""])//判断不是空
    {
        [self.string deleteCharactersInRange:NSMakeRange
         ([self.string length]-1,1)];//删除最后一个字符
        self.scanfLable.text=[NSString stringWithString:_string];//显示结果
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    
    self.tabBarController.tabBar.hidden = NO;
    
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
